package com.pic.mgt.syushin.executer;

import java.io.File;
import java.io.IOException;

import com.pic.mgt.executer.SimpleConfirmationFileMaker;
import com.pic.mgt.file.io.FileOperation;
import com.pic.mgt.log.IgxLog;
import com.pic.mgt.unit.Business;

public class RealConfirmationFileProcess implements CfmtAction {
	// (送多方刪除)
	//private String syushinOutboxRealPathStr;
	// (送多方刪除)
	//private File syushinOutboxRealPath;
	private FileOperation fileOperation;

	@Override
	public void build(Business business, File destFolder)
						throws BuildCfmtFileProcessException {
		// 取得要產生在 syushin outbox real 目錄底下的確檔案
		// (送多方修改)
		File confirmationFileUnderSyushinRealOutbox =
							new File(destFolder.getAbsolutePath(), business.getConfirmationFilename());
		// 取得要產生在 syushin outbox real 目錄底下的暫存確檔案
		File confirmationTmpFileUnderSyushinRealOutbox = SimpleConfirmationFileMaker.
								getTmepConfirmationFile(confirmationFileUnderSyushinRealOutbox);
		
		// (送多方修改)
		// 將 File OK 檔複製到 syushin outbox real 對應的 AP 目錄 底下,並先命名為暫存檔名
		try {
			this.fileOperation.copyFileToFile(business.getConfirmationFile(),
									          confirmationTmpFileUnderSyushinRealOutbox);
		} catch (IOException e1) {
			// (送多方修改) (修改訊息內容　moving 變 copying)
			throw new BuildCfmtFileProcessException(
					"Generating confirmation file for transaction file '" + business.getTargetFilename() +
					"' failed in the following step: copying confirmation file '" + confirmationFileUnderSyushinRealOutbox.getAbsolutePath() + 
					"' to become tmp file '" + confirmationTmpFileUnderSyushinRealOutbox.getAbsolutePath() + "'.",
					e1);
		}
		
		// 將暫存的 File Ok 檔 rename 為正確的檔名
		try {
			this.fileOperation.moveFileToFile(confirmationTmpFileUnderSyushinRealOutbox,
											  confirmationFileUnderSyushinRealOutbox);
		} catch (IOException e1) {
			throw new BuildCfmtFileProcessException(
					"Generating confirmation file for transaction file '" + business.getTargetFilename() +
					"' failed in the following step: renaming tmp confirmation file '" + confirmationTmpFileUnderSyushinRealOutbox.getAbsolutePath() + 
					"' to '" + confirmationFileUnderSyushinRealOutbox.getAbsolutePath() + "' failed.",
					e1);
		}
		
		// ********************** Log **********************
		if (IgxLog.messageDetailsLog.isTraceMode()) {
			IgxLog.messageDetailsLog.trace(this, "Generating confirmation file for transaction file '{}' completed.",
					business.getTargetFilename());
		}
		// ********************** Log **********************
	}
	
	// --- getter and setter ---
	
	// (送多方刪除)
	/*public void setSyushinOutboxRealPathStr(String syushinOutboxRealPathStr) {
		this.syushinOutboxRealPathStr = syushinOutboxRealPathStr;
		this.syushinOutboxRealPath = new File(syushinOutboxRealPathStr);
	}*/

	public void setFileOperation(FileOperation fileOperation) {
		this.fileOperation = fileOperation;
	}
}
